package com.nio.c4_黏包半包;

import java.nio.ByteBuffer;

/**
 * @version No one is coming, unless you change yourself!!!
 * @author： pang-yun
 * @date： 2021-05-31 11:49
 */

public class ExamByMy {
    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        byteBuffer.put("No one is coming\nunless yo".getBytes());
        split(byteBuffer);
        byteBuffer.put("u change yourself\n".getBytes());
        split(byteBuffer);
    }

    public static void split(ByteBuffer byteBuffer) {
        byteBuffer.flip();
        for (int i=0;i<byteBuffer.limit();i++){
            if (byteBuffer.get(i)=='\n'){
                int length = i + 1 - byteBuffer.position();
                ByteBuffer newBuffer = ByteBuffer.allocate(length);
                for (int j=0;j<length;j++){
                    newBuffer.put(byteBuffer.get());
                }
                read(newBuffer);
            }
        }
        byteBuffer.compact();
    }
    public static void read(ByteBuffer byteBuffer){
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()){
            byte b = byteBuffer.get();
            System.out.print((char)b);
        }

    }
}
